package com.app.utils;

import com.app.config.Settings;

import java.io.*;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;

//@Component//单例设计模式
public class FileLogUtils {
    public static String ACTION_FILE_MKDIR = "mkdir";
    public static String ACTION_FILE_UPLOAD = "upload";
    public static String ACTION_FILE_DELETE = "delete";
    public static String ACTION_FILE_DOWNLOAD= "download";
    public static String ACTION_FILE_RENAME= "rename";
    public static String ACTION_FILE_COPY= "copy";
    public static String ACTION_SHARE_ADD= "addShare";
    public static String ACTION_SHARE_DEL= "delShare";
    public static String ACTION_SHARE_EDIT= "editShare";
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/DD-HH:mm:ss");
    /**
     * 添加一跳日志，日志内容包括（操作者，操作时间，行为，内容），时间不用再参数指定
     * @param userId 操作者id
     * @param action 行为
     * @param msg 内容
     * @return 系统错误或未打开日志，则返回 false
     */
    public static boolean addLog(String userId,String action,String msg){
        String time = dateFormat.format(new Date());
        File file = Paths.get(Settings.usersDir,userId,"/log-1.dat").toFile();
        if (!file.isFile()) return false;//如果为关闭日志
        try {
            PrintWriter printWriter=new PrintWriter(new FileWriter(file,true));
            printWriter.append(action+" "+time+" "+msg+"/n");
            printWriter.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    public static String[] getLogs(String userId){
        File file = new File(Settings.rootsDir+"/"+userId+"/log");
        try {
            if (!file.isFile()) file.createNewFile();
            FileReader fileReader=new FileReader(file);
            StringBuilder stringBuilder=new StringBuilder();
            char[] buf=new char[1024];
            while (fileReader.read(buf)>0) stringBuilder.append(buf);
            fileReader.close();
            return stringBuilder.toString().trim().split("/n");
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
